#include <iostream>

#include <unistd.h>
#include <pthread.h>

pthread_t maintid;

void* threadRun(void* args)
{
    uint64_t number = (uint64_t)args;

    while (true)
    {
        if (number == 0)
        {
            std::cout << "number: 0 self cancel" << std::endl;
            pthread_cancel(pthread_self());
            sleep(1);
        }
        std::cout << "number: " << number << " running..." << std::endl;
        sleep(1);
        if (number == 4)
        {
            sleep(12);
            std::cout << "cancel main thread" << std::endl; 
            pthread_cancel(maintid);
            while (true)
            {
                std::cout << "number 4 running..." << std::endl;
                sleep(1);
            }
        }
    }

    return nullptr;
}

int main()
{
    pthread_t tids[5];
    for (uint64_t i = 0; i < 5; ++i)
        pthread_create(tids + i, nullptr, threadRun, (void*)i);

    sleep(3);
    for (int i = 1; i < 4; ++i)
    {
        std::cout << "number: " << i << " main cancel" << std::endl;
        pthread_cancel(tids[i]);
        sleep(1);
    }
    maintid = pthread_self();
    while (true)
    {
        std::cout << "main thread running..." << std::endl;
        sleep(1);
    }
    return 0;
}